package org.trademarket.trader;

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.trademarket.trader.domain.Consumer;
import org.trademarket.trader.domain.Seller;
import org.trademarket.trader.domain.Trade;
import org.trademarket.trader.domain.Trader;

public class Runner {

	public static void main(String[] args) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-context.xml");
		
		TradeTrackerService tradeTracker = ctx.getBean(TradeTrackerService.class);

		List<Trader> traders = generateRandomTraders(5);
		sendTrades(tradeTracker, traders);
	}

	private static List<Trader> generateRandomTraders(int count) {
		List<Trader> traders = new ArrayList<Trader>(count);
		for (int i = 0; i < count; i++) {
			Trader trader = getRandomTrader("Trader " + i);
			trader.setTradeToPropose(getRandomTrade(i));
			traders.add(trader);
		}
		return traders;
	}

	private static void sendTrades(TradeTrackerService tradeTracker,
			List<Trader> traders) {
		for (Trader trader : traders) {
			tradeTracker.send(trader.propose());
		}
	}

	private static Trader getRandomTrader(String name) {
		if (getRandomInt(1) == 0) {
			return new Seller(name);
		} else {
			return new Consumer(name);
		}
	}

	private static Trade getRandomTrade(int i) {
		return new Trade(getRandomProduct(), getRandomAmount(i));
	}

	private static String getRandomProduct() {
		return getRandomInt(1) == 0 ? "USD" : "EUR";
	}

	private static int getRandomAmount(int index) {
		return 100 + index % 3 * 200;
	}

	private static int getRandomInt(int maxInt) {
		return (int) (Math.random() * (maxInt + 1));
	}

}
